
import CryptoTool from '@/common/utils/crypto/jscrypto.js'
import { app_channel,app_base_path, app_base_url,app_key,kPageCount } from '@/common/config/config.js'

const requestInterceptors=(vm)=>{
	/**
	 * 请求拦截
	 * @param {Object} http
	 */
	uni.$uv.http.interceptors.request.use((config) => { 
		const data = config.data || {}
		console.log('请求接口：',config.url)
		if(config.custom.page) {
			config.data = getMeta(data,config.custom.page)
		}
		else{
			config.data = getMeta(data)
		}
		if (config.custom.show) {
			uni.$utils.showLoading(config.custom.title, config.custom.mask)
		}
		return config
	}, (config) => 
		Promise.reject(config))
}
const responseInterceptors=(vm)=>{
	/**
	 * 响应拦截
	 * @param {Object} http 
	 */
	uni.$uv.http.interceptors.response.use((response) => { 
		// 自定义参数
		const custom = response.config?.custom
		if (custom.show) {
			uni.$utils.hideLoading()
		}
		let encryptData = response.data
		//解密结果字符串
		const decryptRes = CryptoTool.networkDecrypt(encryptData)
		if(uni.$uv.test.empty(decryptRes)){
			uni.$utils.showToast('数据响应异常')
			return Promise.reject('')
		}
		//解密结果json
		const data = JSON.parse(decryptRes)
		console.log('请求结果：',data)
		if (data.meta.statusCode != 200) {
			// 错误是结束下拉/上拉加载更多组件状态
			uni.$emit('z-paging-error-emit');
			if (data.message.content) {
				uni.$utils.showToast(data.message.content)
			}
			if(data.message.code == 'E00401' || data.message.code == 'E11001'){
				if(uni.$auth.isLogin()) {
					uni.$auth.logout()
				}
				return Promise.reject('')
			}
			else{
				return Promise.reject(data)
			}
		}
		return data || {}
	}, (response) => { 
		console.log(response)
		uni.$utils.showToast('似乎与网络断开了连接~')
		// 错误是结束下拉/上拉加载更多组件状态
		uni.$emit('z-paging-error-emit');
		return Promise.reject('')
	})
}

//  初始化请求配置
const initRequest=(vm)=>{
	uni.$uv.http.setConfig((defaultConfig) => {
		/* defaultConfig 为默认全局配置 */
		// #ifdef H5
		defaultConfig.baseURL = app_base_path()
		// #endif
		// #ifndef H5
		defaultConfig.baseURL = `${app_base_url()}${app_base_path()}`
		// #endif
		defaultConfig.header = {'Accept':'application/x-json;charset=utf-8','Content-Type':'application/x-json','channel':app_channel()}
		defaultConfig.timeout = 60000
		return defaultConfig
	})
	requestInterceptors()
	responseInterceptors()
}

/**
 * 组装请求Meta信息
 * @type {Function}
 * @param {object} data 请求参数对象
 * @param {number} page 当前页数，为0时不分页
 * @returns {string} 返回加密结果字符串
 */
const getMeta = (data = {}, page = 0) => {
	const transDate = uni.$uv.timeFormat(new Date().getTime(), 'yyyymmddhhMMss')
	//#ifdef H5
	const clientName = 'H5'
	// #endif
	//#ifdef MP-WEIXIN
	const clientName = 'wx'
	// #endif
	//#ifdef APP-PLUS
	const clientName = 'APP'
	// #endif
	const appKey = app_key()
	const transNonce = uni.$uv.guid(32)
	const clientVersion = '1.0.0'
	let system = uni.getStorageSync('system')
	if (!system) {
		system = uni.$uv.sys().system //系统版本
		uni.setStorageSync('system', system)
	}
	let meta = {
		transDate,
		clientName,
		clientVersion,
		appKey,
		transNonce,
		extension: system
	}
	const token = uni.$auth.getToken()
	if (!uni.$uv.test.empty(token)) {
		meta.accessToken = token
	}
	let newData = {
		data,
		meta
	}
	if (page > 0) {
		newData.page = {
			"pageNumber": page,
			"pageSize": kPageCount
		}
	}
	console.log('请求参数：',newData)
	return CryptoTool.networkEncrypt(JSON.stringify(newData))
}
export {
	initRequest
}